package cn.edu.tju.elm.controller;

import cn.edu.tju.core.model.HttpResult;
import cn.edu.tju.core.model.ResultCodeEnum;
import cn.edu.tju.core.model.User;
import cn.edu.tju.core.security.SecurityUtils;
import cn.edu.tju.core.security.rest.dto.LoginDto;
import cn.edu.tju.core.security.rest.dto.LoginResponse;
import cn.edu.tju.core.security.service.UserService;
import cn.edu.tju.core.security.jwt.TokenProvider;
import cn.edu.tju.elm.model.Business;
import cn.edu.tju.elm.service.BusinessService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;

@RestController
@RequestMapping("/api/auth")
@Tag(name = "认证管理", description = "提供用户认证相关功能")
public class AuthController {

    @Autowired
    private UserService userService;

    @Autowired
    private BusinessService businessService;

    private final TokenProvider tokenProvider;
    private final AuthenticationManagerBuilder authenticationManagerBuilder;

    public AuthController(TokenProvider tokenProvider, AuthenticationManagerBuilder authenticationManagerBuilder) {
        this.tokenProvider = tokenProvider;
        this.authenticationManagerBuilder = authenticationManagerBuilder;
    }

    @PostMapping("/login")
    @Operation(summary = "用户登录", description = "用户登录验证，返回JWT token")
    public HttpResult<LoginResponse> login(@RequestBody LoginDto loginDto) {
        try {
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(loginDto.getUsername(), loginDto.getPassword());

            Authentication authentication = authenticationManagerBuilder.getObject().authenticate(authenticationToken);
            SecurityContextHolder.getContext().setAuthentication(authentication);

            boolean rememberMe = (loginDto.isRememberMe() == null) ? false : loginDto.isRememberMe();
            String jwt = tokenProvider.createToken(authentication, rememberMe);

            Optional<User> userOpt = userService.getUserByUsername(loginDto.getUsername());
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                
                // 检查是否为商家用户，如果是则获取店铺ID
                Long businessId = null;
                boolean isBusiness = user.getAuthorities().stream()
                        .anyMatch(authority -> "BUSINESS".equals(authority.getName()));
                if (isBusiness) {
                    Business business = businessService.getBusinessByUserId(user.getId());
                    if (business != null) {
                        businessId = business.getId();
                    }
                }
                
                LoginResponse response = new LoginResponse(
                        jwt,
                        user.getUsername(),
                        user.getId(),
                        user.getUserImg(),
                        user.getUserSex(),
                        user.getAuthorities(),
                        businessId
                );
                return HttpResult.success(response);
            } else {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED, "用户不存在");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "登录失败: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    @Operation(summary = "用户登出", description = "用户登出，清除认证信息")
    public HttpResult<String> logout() {
        // 在实际项目中，这里应该将token加入黑名单或清除session
        return HttpResult.success("登出成功");
    }

    @GetMapping("/verify")
    @Operation(summary = "验证token", description = "验证当前token是否有效")
    public HttpResult<User> verifyToken() {
        try {
            Optional<User> userOpt = userService.getUserWithAuthorities();
            if (userOpt.isPresent()) {
                User user = userOpt.get();
                // 清除密码信息
                user.setPassword(null);
                return HttpResult.success(user);
            } else {
                return HttpResult.failure(ResultCodeEnum.UNAUTHORIZED, "Token无效或已过期");
            }
        } catch (Exception e) {
            return HttpResult.failure(ResultCodeEnum.SERVER_ERROR, "Token验证失败: " + e.getMessage());
        }
    }
}